<template>
	<div>
		<el-card>
			<el-form :model="state.pageParam.param" label-width="120" ref="queryFormRef" @keyup.enter.enter="loadList">
				<el-row :gutter="10">
					<el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
						<el-form-item prop="formCode" label="编号">
							<el-input v-model="state.pageParam.param.formCode" placeholder="编号" clearable> </el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
						<el-form-item prop="formName" label="名称">
							<el-input v-model="state.pageParam.param.formName" placeholder="名称" clearable> </el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
						<el-form-item prop="formType" label="表单类型">
							<DicSelect v-model="state.pageParam.param.formType" placeholder="请选择表单类型" dicCode="devFormType" style="width: 100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="6" :lg="8" :xl="8">
						<el-form-item prop="remark" label="备注">
							<el-input v-model="state.pageParam.param.remark" placeholder="备注" clearable> </el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="btnSearchStyle">
				<el-button type="primary" class="ml7" @click="loadList">
					<el-icon>
						<ele-Search />
					</el-icon>
					查询
				</el-button>
				<el-button type="primary" class="ml10" @click="reSetForm(queryFormRef)">
					<el-icon>
						<ele-Refresh />
					</el-icon>
					重置
				</el-button>
			</div>
		</el-card>
		<el-card>
			<div class="btnStyle">
				<el-button type="success" icon="ele-Plus" @click="addOrUpdateHandle()">新增</el-button>
			</div>
			<el-table :data="state.dataList" style="width: 100%">
				<el-table-column prop="formCode" header-align="center" align="center" label="编号" />
				<el-table-column prop="formName" header-align="center" align="center" label="名称" />
				<el-table-column prop="formType" header-align="center" align="center" label="表单类型" column-key="devFormType" :formatter="formatStatus" />
				<el-table-column prop="remark" header-align="center" align="center" label="备注" />
				<el-table-column
					prop="resStatus"
					header-align="center"
					align="center"
					label="是否已发布"
					column-key="SCREEN_STATUS"
					:formatter="formatStatus"
				/>
				<el-table-column fixed="right" header-align="center" align="center" label="操作">
					<template #default="scope">
						<el-button type="primary" link @click="updateHandle(scope.row)">修改</el-button>
						<el-button type="primary" link @click="setApiHandle(scope.row)">设置外部接口</el-button>
						<el-button type="primary" link @click="releaseHandle(scope.row)">发布</el-button>
						<el-button type="primary" link @click="deleteHandle(scope.row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="onHandleSizeChange"
				@current-change="onHandleCurrentChange"
				:pager-count="5"
				:page-sizes="[10, 50, 200]"
				v-model:current-page="state.pageParam.page"
				background
				v-model:page-size="state.pageParam.pageSize"
				layout="total, sizes, prev, pager, next, jumper"
				:total="state.total"
				small
			>
			</el-pagination>
		</el-card>
		<el-dialog
			fullscreen
			:destroy-on-close="true"
			:close-on-click-modal="false"
			:close-on-press-escape="addOrUpdatecloseFn"
			:before-close="addOrUpdatecloseFn"
			:append-to-body="true"
			:title="!state.submitForm.id ? '新增' : '修改'"
			ref="addOrUpdate"
			v-model="state.addOrUpdateVisible"
			width="100%"
		>
			<el-form
				:model="state.submitForm"
				:rules="state.submitFormRule"
				ref="ruleFormRef"
				@keyup.enter.enter="dataFormSubmit(ruleFormRef)"
				label-width="120px"
			>
				<el-row :gutter="10">
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="编号" prop="formCode">
							<el-input v-model="state.submitForm.formCode" placeholder="编号" maxlength="255"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="名称" prop="formName">
							<el-input v-model="state.submitForm.formName" placeholder="名称" maxlength="255"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="表单类型" prop="formType">
							<DicSelect v-model="state.submitForm.formType" placeholder="请选择表单类型" dicCode="devFormType" style="width: 100%"></DicSelect>
						</el-form-item>
					</el-col>
					<el-col :xs="3" :sm="4" :md="4" :lg="6" :xl="6">
						<el-form-item label="备注" prop="remark">
							<el-input v-model="state.submitForm.remark" placeholder="备注" maxlength="255"></el-input>
						</el-form-item>
					</el-col>
				</el-row>

				<div class="container">
					<el-button type="primary" @click="fieldSetHandle">表单字段设置</el-button>
				</div>
			</el-form>
			<v-form-designer ref="vfDesigner" :designer-config="{ languageMenu: false, externalLink: false, generateSFCButton: false, logoHeader: false }">
			</v-form-designer>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="state.addOrUpdateVisible = false">取消</el-button>
					<el-button type="primary" @click="dataFormSubmit(ruleFormRef)">保存</el-button>
					<el-button type="primary" @click="SubmitRelease(ruleFormRef)">保存并发布</el-button>
				</span>
			</template>

			<!-- :destroy-on-close='true' 这里不用销毁弹框中的元素，避免配置完字段后，再次打开弹框时数据清空掉了-->
			<el-dialog
				:close-on-click-modal="false"
				:close-on-press-escape="fieldDesigncloseFn"
				:before-close="fieldDesigncloseFn"
				title="表单字段设置"
				ref="addOrUpdate"
				v-model="state.fieldDesignVisible"
				width="80%"
				:open-delay="200"
				:destroy-on-close="true"
			>
				<formFieldDesign ref="formFieldDesignRef" :tab_obj="state.format" @closeSetup="close_setup"></formFieldDesign>
				<template #footer>
					<div class="box_btn">
						<el-button type="primary" @click="designSubmitFn">保存配置</el-button>
					</div>
				</template>
			</el-dialog>
		</el-dialog>

		<el-dialog
			:destroy-on-close="true"
			:close-on-click-modal="false"
			:close-on-press-escape="(setApiDesignVisible = false)"
			:before-close="(setApiDesignVisible = false)"
			title="设置外部接口"
			ref="setApi_dialog"
			v-model="state.setApiDesignVisible"
			width="85%"
			:open-delay="200"
		>
			<setApi ref="setApi_ref"></setApi>

			<template #footer>
				<div class="">
					<el-button type="primary" @click="subFn()">保存接口配置</el-button>
					<el-button type="" @click="state.setApiDesignVisible = false">取消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>
<script setup lang="ts" name="sysFormDesigner">
import { ElMessage, ElMessageBox, FormInstance, ElLoading } from 'element-plus';
import { ref, reactive, onMounted, defineAsyncComponent, nextTick } from 'vue';
import { SysFormDesigner, developApi } from '/@/api/sys/develop-api';
import { getDataDictionaryList } from '/@/utils/cacheDic';
import { parseScript, processDynamicValues } from '/@/utils/scriptParser';
const formFieldDesign = defineAsyncComponent(() => import('./formFieldDesign.vue')); // 表单字段设置
const setApi = defineAsyncComponent(() => import('./setApi.vue')); // 外部接口设置
const queryFormRef = ref<FormInstance>();
const ruleFormRef = ref<FormInstance>();
const vfDesigner = ref<any>();
const formFieldDesignRef = ref();
const setApi_ref = ref();
const state = reactive({
	transientData: {} as any,
	row_id: '',
	listLoading: false,
	total: 0,
	dataList: [] as SysFormDesigner['records'],
	dataListSelections: [],
	dataDictionaryList: [] as any,
	pageParam: {
		page: 1,
		pageSize: 10,
		param: {
			id: '',
			version: '',
			formCode: '',
			formName: '',
			formType: '',
			remark: '',
			formDesJson: '',
		},
	},
	addOrUpdateVisible: false,
	submitForm: {
		id: '',
		version: 0,
		formCode: '',
		formName: '',
		formType: '',
		remark: '',
		formDesJson: '',
		resStatus: '0',
	},
	submitFormRule: {
		formCode: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
		formName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
		formType: { required: true, message: '请选择表单类型', trigger: 'change' },
	},
	formJson: {
		widgetList: [],
		formConfig: {
			modelName: 'formData',
			refName: 'vForm',
			rulesName: 'rules',
			labelWidth: 80,
			labelPosition: 'left',
			size: '',
			labelAlign: 'label-left-align',
			cssCode: '',
			class: '',
			functions: '',
			layoutType: 'PC',
			jsonVersion: 3,
			onFormCreated: '',
			onFormMounted: '',
			onFormDataChange: '',
			onFormValidate: '',
		},
	},
	fieldDesignVisible: false,
	format: {} as any,
	setApiDesignVisible: false,
});

const subFn = () => {
	if (!setApi_ref.value.setForm_ref) return;
	setApi_ref.value.setForm_ref.validate((valid: boolean) => {
		if (!valid) return;
		// setApi_ref.value.datas.setForm.dataTab.forEach((item: any) => {
		// 	item.apiHeadScript = parseScript(item.apiHead, '请求头脚本');
		// 	item.apiBodyScript = parseScript(item.apiBody, '请求体脚本');
		// });

		// nextTick(() => {
		// 	setApi_ref.value.datas.setForm.dataTab.forEach((t: any) => {
		// 		t.apiHeadScript = processDynamicValues(t.apiHead);
		// 		t.apiBodyScript = processDynamicValues(t.apiBody);
		// 	});
		// });
		var param = {
			id: state.row_id,
			apiList: setApi_ref.value.datas.setForm.dataTab,
		};
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		});
		developApi
			.setDesignerApi(param)
			.then((data) => {
				if (data && data.code == 0) {
					state.setApiDesignVisible = false;
					ElMessage.success('保存接口配置成功');
				} else {
					ElMessage.error(data.message);
				}
			})
			.catch(() => {
				ElMessage.error('保存接口配置失败');
			})
			.finally(() => {
				loading.close();
			});
	});
};

const setApiHandle = (row: any) => {
	state.row_id = row.id;
	state.setApiDesignVisible = true;
};

const designSubmitFn = () => {
	formFieldDesignRef.value?.submitForm();
	state.transientData = formFieldDesignRef.value?.datas.dataForm;
	window.console.log(state.transientData, 'state.transientData');
};

const close_setup = (val: any) => {
	state.fieldDesignVisible = val;
};

const fieldDesigncloseFn = () => {
	ElMessageBox.confirm('确定关闭表单字段设置弹框?', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	})
		.then(() => {
			state.fieldDesignVisible = false;
		})
		.catch(() => {});
};

//格式化表单字段设置表格数据
const formatData = (data: object) => {
	let main = [];
	let sub = {};
	for (let key in data) {
		if (typeof data[key] === 'object') {
			// 处理子表单
			sub[key] = Object.keys(data[key]).map((subKey) => ({
				widgetName: subKey,
				columnName: '',
				columnType: '', //data[key][subKey]
				columnLength: '',
				places: '',
				columnDes: '',
				primary: 'false',
				required: 'false',
			}));
		} else {
			// 处理主表单
			main.push({
				widgetName: key,
				columnName: '',
				columnType: '', //data[key]
				columnLength: '',
				places: '',
				columnDes: '',
				primary: 'false',
				required: 'false',
			});
		}
	}
	return { main, sub };
};

//关闭弹框后清空内置弹框的表格数据(内置弹框关闭时未销毁，会有缓存数据需要手动清空)
const addOrUpdatecloseFn = () => {
	state.addOrUpdateVisible = false;
	state.format = {};
};

// 打开表单设计弹框
const fieldSetHandle = () => {
	const tab = vfDesigner.value?.buildFormDataSchema(); // 获取表单设计器组件字段名称及组件类型
	if (!tab || Object.keys(tab).length === 0) {
		ElMessage.error('请先拖拽需要的组件或子表单后，再进行表单字段设置配置');
		return;
	}

	nextTick(() => {
		state.format = formatData(tab);
		if (Object.keys(state.transientData).length > 0) {
			// 处理主表数据
			updateMainTabFields(state.format.main, state.transientData.mainTab);

			// 处理子表数据
			updateSubTabFields(state.format.sub, state.transientData.subTab);
		}

		nextTick(() => {
			state.fieldDesignVisible = true;
		});
	});
};

// 更新主表字段
const updateMainTabFields = (mainTab: any[], transientMainTab: any[]) => {
	for (const item of mainTab) {
		const matchedItem = transientMainTab.find((t: any) => t.widgetName === item.widgetName);
		if (matchedItem) {
			Object.assign(item, {
				columnDes: matchedItem.columnDes,
				columnLength: matchedItem.columnLength,
				columnName: matchedItem.columnName,
				columnType: matchedItem.columnType,
				places: matchedItem.places,
				primary: matchedItem.primary,
				required: matchedItem.required,
			});
		}
	}
};

// 更新子表字段
const updateSubTabFields = (subTab: Record<string, any[]>, transientSubTab: Record<string, any[]>) => {
	for (const [key, array] of Object.entries(subTab)) {
		for (const item of array) {
			for (const [subKey, subArray] of Object.entries(transientSubTab)) {
				const matchedItem = subArray.find((t: any) => t.widgetName === item.widgetName);
				if (matchedItem) {
					Object.assign(item, {
						columnDes: matchedItem.columnDes,
						columnLength: matchedItem.columnLength,
						columnName: matchedItem.columnName,
						columnType: matchedItem.columnType,
						places: matchedItem.places,
						primary: matchedItem.primary,
						required: matchedItem.required,
					});
				}
			}
		}
	}
};

//保存并发布
const SubmitRelease = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;

		ElMessageBox.confirm('是否设置数据库表单字段?(如已设置请忽略)', '提示', {
			confirmButtonText: '确定保存并发布',
			cancelButtonText: '取消',
		})
			.then(() => {
				let tab = vfDesigner.value?.buildFormDataSchema();
				if (Object.keys(tab).length > 0) {
					state.format = formatData(tab);
				} else {
					state.format = {
						main: [],
						sub: [],
					};
				}
				state.submitForm.formDesJson = JSON.stringify(vfDesigner.value?.getFormJson());
				state.submitForm.resStatus = '1';
				let params = reactive({} as any);
				params = state.submitForm;
				let JsonTab = JSON.stringify({
					main: formFieldDesignRef.value?.datas.dataForm.mainTab ? formFieldDesignRef.value?.datas.dataForm.mainTab : state.format.main,
					sub: formFieldDesignRef.value?.datas.dataForm.subTab ? formFieldDesignRef.value?.datas.dataForm.subTab : state.format.sub,
				});
				params.formColumnJson = JsonTab;
				//提交数据
				const loading = ElLoading.service({
					lock: true,
					text: '处理中',
					background: 'rgba(0, 0, 0, 0.7)',
				});
				if (!params.id) {
					//新增
					developApi
						.saveSysFormDesignerInfo(params)
						.then((data) => {
							if (data && data.code === 0) {
								ElMessage.success('保存并发布成功');
								state.addOrUpdateVisible = false;
								state.format = {};
								loadList();
							} else {
								ElMessage.error(data.message);
							}
						})
						.catch(() => {
							ElMessage.error('保存失败');
						})
						.finally(() => {
							loading.close();
						});
				} else {
					developApi
						.updateSysFormDesignerInfo(params)
						.then((data) => {
							if (data && data.code === 0) {
								ElMessage.success('保存并发布成功');
								state.addOrUpdateVisible = false;
								state.format = {};
								loadList();
							} else {
								ElMessage.error(data.message);
							}
						})
						.catch(() => {
							ElMessage.error('保存失败');
						})
						.finally(() => {
							loading.close();
						});
				}
			})
			.catch(() => {});
	});
};

//发布
const releaseHandle = (row: any) => {
	ElMessageBox.confirm('是否确定发布所选记录', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		const loading = ElLoading.service({
			lock: true,
			text: '处理中',
			background: 'rgba(0, 0, 0, 0.7)',
		});
		let param = {
			id: row.id,
			version: 0,
			formCode: row.formCode,
			formName: row.formName,
			formType: row.formType,
			remark: '',
			formDesJson: '',
			resStatus: '1',
		};
		developApi
			.releaseSysFormDesignerInfo(param)
			.then((data) => {
				if (data && data.code == 0) {
					ElMessage.success('发布成功');
					loadList();
				} else {
					ElMessage.error(data.message);
				}
			})
			.catch(() => {
				ElMessage.error('发布失败');
			})
			.finally(() => {
				loading.close();
			});
	});
};

const loadList = () => {
	state.listLoading = true;
	developApi
		.querySysFormDesignerListPage(state.pageParam)
		.then((data) => {
			if (data && data.code === 0) {
				state.dataList = data.data.records;
				state.total = data.data.totalRow;
			} else {
				state.dataList = [];
				state.total = 0;
			}
		})
		.catch(() => {})
		.finally(() => {
			state.listLoading = false;
		});
};
// 页面加载时
onMounted(() => {
	// 数据字典
	getDataDictionaryList(state.dataDictionaryList, ['devFormType', 'SCREEN_STATUS']);
	// 列表查询
	loadList();
});

//重置
const reSetForm = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.resetFields();
	state.pageParam.page = 1;
	loadList();
};
// 分页改变
const onHandleSizeChange = (val: number) => {
	state.pageParam.pageSize = val;
	loadList();
};
// 分页改变
const onHandleCurrentChange = (val: number) => {
	state.pageParam.page = val;
	loadList();
};
//删除
const deleteHandle = (id: string | undefined) => {
	if (!id) {
		ElMessage.error('请选择记录！');
		return;
	}
	ElMessageBox.confirm('是否确定删除所选记录', '提示', {
		confirmButtonText: '确定',
		cancelButtonText: '取消',
	}).then(() => {
		developApi
			.deleteSysFormDesignerInfo(id)
			.then((data) => {
				if (data && data.code === 0) {
					ElMessage.success('删除成功');
					loadList();
				} else {
					ElMessage.error(data.message);
				}
			})
			.catch(() => {
				ElMessage.error('删除失败');
			});
	});
};
//打开新增弹窗
const addOrUpdateHandle = () => {
	state.submitForm = {
		id: '',
		version: 0,
		formCode: '',
		formName: '',
		formType: '',
		remark: '',
		formDesJson: '',
		resStatus: '',
	};
	state.addOrUpdateVisible = true;
	nextTick(() => {
		vfDesigner.value?.setFormJson(state.formJson);
	});
};
//打开修改弹窗
const updateHandle = (row: any | undefined) => {
	state.submitForm = {
		id: row.id,
		version: row.version,
		formCode: row.formCode,
		formName: row.formName,
		formType: row.formType,
		remark: row.remark,
		formDesJson: row.formDesJson,
		resStatus: row.resStatus,
	};
	state.addOrUpdateVisible = true;
	nextTick(() => {
		vfDesigner.value?.setFormJson(row.formDesJson);
		if (row.formColumnJson && (row.formColumnJson != null || row.formColumnJson != undefined)) {
			state.format = JSON.parse(row.formColumnJson);
		}
	});
};
//新增修改提交
const dataFormSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (valid) {
			//提交数据
			const loading = ElLoading.service({
				lock: true,
				text: '处理中',
				background: 'rgba(0, 0, 0, 0.7)',
			});
			state.submitForm.formDesJson = JSON.stringify(vfDesigner.value?.getFormJson());
			if (!state.submitForm.id) {
				//新增
				developApi
					.saveSysFormDesignerInfo(state.submitForm)
					.then((data) => {
						if (data && data.code === 0) {
							ElMessage.success('保存成功');
							state.addOrUpdateVisible = false;
							state.format = {};
							loadList();
						} else {
							ElMessage.error(data.message);
						}
					})
					.catch(() => {
						ElMessage.error('保存失败');
					})
					.finally(() => {
						loading.close();
					});
			} else {
				developApi
					.updateSysFormDesignerInfo(state.submitForm)
					.then((data) => {
						if (data && data.code === 0) {
							ElMessage.success('保存成功');
							state.addOrUpdateVisible = false;
							state.format = {};
							loadList();
						} else {
							ElMessage.error(data.message);
						}
					})
					.catch(() => {
						ElMessage.error('保存失败');
					})
					.finally(() => {
						loading.close();
					});
			}
		}
	});
};

const formatStatus = (row: any, column: any, cellValue: string | number, index: number) => {
	if (Object.keys(state.dataDictionaryList).length > 0) {
		if (cellValue) {
			return state.dataDictionaryList[column.columnKey].get(cellValue);
		}
	}
};
</script>

<style scoped>
.container {
	display: flex;
	justify-content: flex-end; /* 将内容推到右边 */
}
.box_btn {
	display: flex;
	justify-content: center; /* 将内容推到右边 */
}
</style>
